package com.example.ecas.service.impl;

import com.example.ecas.persistence.DiseaseMapper;
import com.example.ecas.persistence.TagMapper;
import com.example.ecas.pojo.DisRtag;
import com.example.ecas.pojo.Disease;
import com.example.ecas.pojo.Tag;
import com.example.ecas.service.WordCloudService;
import com.example.ecas.utils.PythonExecutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class WordCloudServiceImpl implements WordCloudService {

    final static String pythonPath = "./ecas/src/main/python/word_cloud.py";

    @Autowired
    TagMapper tagMapper;

    @Autowired
    DiseaseMapper diseaseMapper;

    // 把DisRtag列表处理成生成词云需要的字符串 "内容1,频率1 内容2,频率2 内容3,频率3 ..."
    private String relationsProc(List<DisRtag> relations) {
        StringBuilder result = new StringBuilder();
        for (DisRtag relation : relations) {
            Tag tag = tagMapper.getTag(relation.getTagId());
            result.append(tag!=null ? tag.getContent() : "未知").append(",");
            result.append(relation.getRate()*10).append(" ");
        }
        return result.toString();
    }

    // 生成并返回以base64编码的词云图片数据
    @Override
    public String getWordCloudBase64(List<DisRtag> relations) throws IOException, InterruptedException {
//        String text = relationsProc(relations).trim();
        List<String> args = new ArrayList<>();
        args.add("frequencies");
        args.add(relationsProc(relations).trim());
        List<String> result = PythonExecutor.execPythonFile(pythonPath, args);
        return result.size()>0 ? result.get(0) : null;
    }

    @Override
    public String getWordCloudB64Random(String content) throws IOException, InterruptedException {
        List<String> args = new ArrayList<>();
        args.add("random");
        args.add(content);
        List<String> result = PythonExecutor.execPythonFile(pythonPath, args);
        return result.size()>0 ? result.get(0) : null;
    }


}
